import { type NextRequest, NextResponse } from "next/server"

// 示例数据，当 Supabase 不可用时使用
const samplePolls = [
  {
    id: "sample-poll-1",
    title: "示例投票：您认为AI对教育的影响是什么？",
    description: "这是一个示例投票，用于展示系统功能",
    active: true,
    created_at: new Date(Date.now() - 86400000).toISOString(),
    options: [
      { id: "opt-1", poll_id: "sample-poll-1", text: "非常积极", votes: 3 },
      { id: "opt-2", poll_id: "sample-poll-1", text: "比较积极", votes: 5 },
      { id: "opt-3", poll_id: "sample-poll-1", text: "中立", votes: 2 },
      { id: "opt-4", poll_id: "sample-poll-1", text: "比较消极", votes: 1 },
      { id: "opt-5", poll_id: "sample-poll-1", text: "非常消极", votes: 0 },
    ],
    comments: [
      {
        id: "comment-1",
        poll_id: "sample-poll-1",
        text: "我认为AI可以帮助教师更好地了解学生的学习情况",
        created_at: new Date(Date.now() - 3600000).toISOString(),
      },
      {
        id: "comment-2",
        poll_id: "sample-poll-1",
        text: "希望能有更多关于AI在教育中应用的讨论",
        created_at: new Date(Date.now() - 1800000).toISOString(),
      },
    ],
  },
]

// 本地存储的投票
const localPolls: any[] = []

export async function POST(request: NextRequest) {
  try {
    const { action, data } = await request.json()

    console.log(`API Route - Handling action: ${action}`)

    switch (action) {
      case "checkConnection":
        return NextResponse.json({ connected: false, usingSampleData: true }, { status: 200 })
      case "getActivePolls":
        return NextResponse.json({ polls: samplePolls.filter((p) => p.active), usingSampleData: true }, { status: 200 })
      case "getAllPolls":
        return NextResponse.json({ polls: samplePolls, usingSampleData: true }, { status: 200 })
      case "getPoll":
        const poll = samplePolls.find((p) => p.id === data.id)
        return NextResponse.json({ poll: poll || null, usingSampleData: true }, { status: 200 })
      case "createPoll":
        return handleCreatePoll(data.title, data.description, data.options)
      case "vote":
        return handleVote(data.pollId, data.optionId, data.voterId)
      case "addComment":
        return handleAddComment(data.pollId, data.text)
      case "updatePollStatus":
        return handleUpdatePollStatus(data.id, data.active)
      case "deletePoll":
        return handleDeletePoll(data.id)
      case "saveLocalPoll":
        localPolls.push(data.poll)
        return NextResponse.json({ success: true }, { status: 200 })
      case "getLocalPolls":
        return NextResponse.json({ polls: localPolls }, { status: 200 })
      default:
        return NextResponse.json({ error: "Invalid action" }, { status: 400 })
    }
  } catch (error: any) {
    console.error("API error:", error)
    return NextResponse.json({ error: error.message || "Server error" }, { status: 500 })
  }
}

// 创建新投票
function handleCreatePoll(title: string, description: string, options: string[]) {
  try {
    // 创建一个新的投票
    const newPoll = {
      id: `sample-${Date.now()}`,
      title,
      description: description || null,
      active: true,
      created_at: new Date().toISOString(),
      options: options.map((text, index) => ({
        id: `sample-opt-${Date.now()}-${index}`,
        poll_id: `sample-${Date.now()}`,
        text,
        votes: 0,
      })),
      comments: [],
    }

    // 添加到示例数据中
    samplePolls.unshift(newPoll)

    return NextResponse.json({ poll: newPoll, usingSampleData: true }, { status: 200 })
  } catch (error: any) {
    console.error("Error in createPoll:", error)
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}

// 投票
function handleVote(pollId: string, optionId: string, voterId: string) {
  try {
    // 查找投票
    const poll = samplePolls.find((p) => p.id === pollId)
    if (!poll) {
      return NextResponse.json({ error: "Poll not found" }, { status: 404 })
    }

    // 查找选项
    const option = poll.options.find((o) => o.id === optionId)
    if (!option) {
      return NextResponse.json({ error: "Option not found" }, { status: 404 })
    }

    // 增加票数
    option.votes++

    return NextResponse.json({ success: true, usingSampleData: true }, { status: 200 })
  } catch (error: any) {
    console.error("Error in vote:", error)
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}

// 添加评论
function handleAddComment(pollId: string, text: string) {
  try {
    // 查找投票
    const poll = samplePolls.find((p) => p.id === pollId)
    if (!poll) {
      return NextResponse.json({ error: "Poll not found" }, { status: 404 })
    }

    // 添加评论
    poll.comments.unshift({
      id: `comment-${Date.now()}`,
      poll_id: pollId,
      text,
      created_at: new Date().toISOString(),
    })

    return NextResponse.json({ success: true, usingSampleData: true }, { status: 200 })
  } catch (error: any) {
    console.error("Error in addComment:", error)
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}

// 更新投票状态
function handleUpdatePollStatus(id: string, active: boolean) {
  try {
    // 查找投票
    const poll = samplePolls.find((p) => p.id === id)
    if (!poll) {
      return NextResponse.json({ error: "Poll not found" }, { status: 404 })
    }

    // 更新状态
    poll.active = active

    return NextResponse.json({ success: true, usingSampleData: true }, { status: 200 })
  } catch (error: any) {
    console.error("Error in updatePollStatus:", error)
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}

// 删除投票
function handleDeletePoll(id: string) {
  try {
    // 查找投票索引
    const pollIndex = samplePolls.findIndex((p) => p.id === id)
    if (pollIndex === -1) {
      return NextResponse.json({ error: "Poll not found" }, { status: 404 })
    }

    // 删除投票
    samplePolls.splice(pollIndex, 1)

    return NextResponse.json({ success: true, usingSampleData: true }, { status: 200 })
  } catch (error: any) {
    console.error("Error in deletePoll:", error)
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}
